const jwt = require('jsonwebtoken');
const db = require('../models/index.js')
const AjaxResult = require('../utils/AjaxResult.js');

class UserController {

  // 登录接口
  async login(ctx, next) {
    const { username, password } = ctx.request.body
    // 查询数据库中是否存在匹配的用户
    const user = await db.User.findOne({ where: { username: username } });
    if (!user) {
      AjaxResult.error(ctx, '401', '用户不存在')
      return;
    }

    // 验证密码是否匹配
    if (user.password !== password) {
      AjaxResult.error(ctx, '401', '用户名或密码错误')
      return;
    }

    // 生成token
    const token = jwt.sign({username, id: user.id}, 'wutapp', {expiresIn: '1h'})

    AjaxResult.success(ctx, token)
  }

  async userInfo (ctx, next) {
    const token = ctx.request.headers.authorization;
  
    // 验证token
    if (!token) {
      AjaxResult.error(ctx, '401', 'token不存在')
      return
    }
  
    try {
      const payload = jwt.verify(token.split(' ')[1], 'wutapp'); // 验证 JWT
      console.log('payload', payload)
      ctx.body = { message: '获取用户信息成功!', code: 200, data: {} };
    } catch (error) {
      console.log('token error ', error)
      ctx.status = 401;
      AjaxResult.error(ctx, '401', 'token 无效')
    }
  }
}

module.exports = new UserController(); // 导出实例